package cn.ziyoufa.smart.smartschool.activity;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.bugly.crashreport.CrashReport;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import cn.ziyoufa.smart.smartschool.R;
import cn.ziyoufa.smart.smartschool.application.PasisApplication;
import cn.ziyoufa.smart.smartschool.db.DBHelper;
import cn.ziyoufa.smart.smartschool.db.DBSqlHelper;
import cn.ziyoufa.smart.smartschool.db.SPManager;
import cn.ziyoufa.smart.smartschool.manager.SchemeManager;
import cn.ziyoufa.smart.smartschool.manager.UpdateManager;
import cn.ziyoufa.smart.smartschool.module.BaseModel;
import cn.ziyoufa.smart.smartschool.module.power.BasePowerModel;
import cn.ziyoufa.smart.smartschool.module.power.PowerValue;
import cn.ziyoufa.smart.smartschool.module.scheme.SchemeValue;
import cn.ziyoufa.smart.smartschool.module.shutdown.ShutdownValue;
import cn.ziyoufa.smart.smartschool.net.RequestCenter;
import cn.ziyoufa.smart.smartschool.okhttp.listener.DisposeDataListener;
import cn.ziyoufa.smart.smartschool.serialport.ComBean;
import cn.ziyoufa.smart.smartschool.serialport.MyFunc;
import cn.ziyoufa.smart.smartschool.serialport.SerialHelper;
import cn.ziyoufa.smart.smartschool.util.NetWorkUtils;
import cn.ziyoufa.smart.smartschool.webview.route.Router;

/**
 * 创建人 ： 赵泽东
 * 创建时间：2018/8/30
 *
 * @param
 * @param
 */
public class LoadingActivity extends BaseActivity {

    static final int a = Build.VERSION.SDK_INT;
    WindowManager.LayoutParams c;
    static Boolean statusBarFlag = true;//true:禁用下拉状态栏，false:启用状态栏

    public static int a(Context paramContext)
    {
        int i = paramContext.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (i > 0) {
            return paramContext.getResources().getDimensionPixelSize(i);
        }
        return 0;
    }

    void a()
    {
        ((WindowManager)getApplicationContext().getSystemService("window")).addView(new View(this), this.c);
    }

    @TargetApi(23)
    public void b()
    {
        if (Settings.canDrawOverlays(this))
        {
            a();
            return;
        }
        startActivityForResult(new Intent("android.settings.action.MANAGE_OVERLAY_PERMISSION", Uri.parse("package:" + getPackageName())), 42715961);
    }

    @TargetApi(23)
    protected void onActivityResult(int paramInt1, int paramInt2, Intent paramIntent)
    {
        if (paramInt1 == 42715961)
        {
            if (Settings.canDrawOverlays(this)) {
                a();
            }
        }
        else {
            return;
        }
        Toast.makeText(this, "Overlay Permission Denied!", 1).show();
        finish();
    }

    /**
     * UI
     */
    private ProgressBar progressBar;
    private WebView webView;
    private RelativeLayout mCopyLayout;
    private TextView tv_second;
    private RelativeLayout mTopWeb;
    private RelativeLayout mBottomLauncher;
    private LinearLayout mLinearLayoutNoNetWork;
    //设备唯一序列号
    private String mSerialNumber = "";
    //跳过按钮
    private LinearLayout layoutSkip;
    //定时器类
    private MyCountDownTimer mc;
    //监听网络是否通的状态
    private Boolean mNetWorkStatus = false;
    //检测是否已经加载了webview,true:还有加载，false：已经加载了
    private Boolean mLoadWebviewStatus = true;
    //是否有新开关机数据写入sqllite,true:有，false:没有
    private static Boolean mShutdownFlag = true;
    //判断当前是否是关机状态，避免重复加载关机指令，如果true：已经是关机状态
    private static Boolean mPowerOffStatus = false;
    //写入服务器开机日志
    private static Boolean mPowerOnRecordStatus = false;

    //A83定时任务
    static SerialControl com;
    private static Boolean sendA83Status = false;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        hiddenStatusBar();
        setContentView(R.layout.activity_loading_layout);
        //判断是否禁用下拉显示状态栏
        statusBarFlag = SPManager.getInstance().getBoolean("statusBarFlag", true);
        if(statusBarFlag){
            this.c = new WindowManager.LayoutParams();
            this.c.type = 2010;
            this.c.gravity = 48;
            this.c.flags = 296;
            this.c.width = -1;
            this.c.height = a(this);
            this.c.format = -2;
            b();
        }
        //屏蔽底部导航
        //mSerialNumber = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID) + Build.SERIAL;
        mSerialNumber = getMAC_Address(LoadingActivity.this);
        SPManager.getInstance().putString("token", mSerialNumber);//保存设备serial
        mPowerOffStatus = false;
        //初始化activity的控件
        initView();
        //检测是否连接网络
        checkNetWork();
        //开始定时任务
        startTimerTask();
        //测试串口通信
        initAndroidSerial();
        //开启线程监听开关机计划任务
        new TimeThread().start();
    }

    public static int getLocalVersion(Context ctx) {
        int localVersion = 0;
        try {
            PackageInfo packageInfo = ctx.getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(ctx.getPackageName(), 0);
            localVersion = packageInfo.versionCode;
            Log.d("TAG", "本软件的版本号。。" + localVersion);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersion;
    }

    //初始化视图控件
    private void initView(){
        mTopWeb   = (RelativeLayout) findViewById(R.id.topWeb);
        mCopyLayout = (RelativeLayout) findViewById(R.id.content_layout);
        tv_second   = (TextView) findViewById(R.id.tv_second);
        layoutSkip = (LinearLayout) findViewById(R.id.layout_skip);
        //点击跳过按钮，进入主页面
        layoutSkip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            mTopWeb.setVisibility(View.VISIBLE);
            mCopyLayout.setVisibility(View.GONE);
            initAndroidSerial();//启动串口通信
            }
        });
        //显示整个加载视图
        mCopyLayout.setVisibility(View.VISIBLE);
        //webview视图里的等待框
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        //webview视图
        webView = (WebView) findViewById(R.id.webView);
        // 底部公司简介
        mBottomLauncher = findViewById(R.id.cpoyright_layout);
        // 没有网络
        mLinearLayoutNoNetWork = findViewById(R.id.no_network);
    }
    private String getMAC_Address(Context context){
        WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        return wm.getConnectionInfo().getMacAddress();
    }
    //检测版本更新
    public void checkAndroidVersion(){
        UpdateManager updateAndGetPermission = new UpdateManager(LoadingActivity.this);
        updateAndGetPermission.verifyStoragePermissions(LoadingActivity.this);
        updateAndGetPermission.checkUpdate();
    }
    //检测网络是否通
    private void checkNetWork(){
        NetWorkUtils.isNetWorkAvailable("www.baidu.com", new Comparable<Boolean>() {
            @Override
            public int compareTo(@NonNull Boolean available) {
                if(available){
                    // TODO 设备访问Internet正常
                    mNetWorkStatus = true;
                    //显示跳过按钮
                    layoutSkip.setVisibility(View.VISIBLE);
                    if(mPowerOnRecordStatus) return 0;
                    mPowerOnRecordStatus = true;
                    //给服务器回传开机时间
                    RequestCenter.sendPowerOnRecord(MyFunc.getCurrentY_M_DHMS(), new DisposeDataListener(){
                        @Override
                        public void onSuccess(Object responseObj) {
                            //成功
                            BasePowerModel mBasePowerModel = (BasePowerModel) responseObj;
                            String status = mBasePowerModel.status;
                            if(status.equals("true")){
                                //服务器返回成功
                            }else{
                                //服务器返回失败
                                PowerValue mPowerValue = new PowerValue();
                                mPowerValue.setCreated_at(MyFunc.getCurrentY_M_DHMS());
                                DBSqlHelper.getInstance().insert(DBHelper.POWER_ON_TABLE, mPowerValue);
                            }
                            //检测版本更新
                            checkAndroidVersion();
                        }

                        @Override
                        public void onFailure(Object reasonObj) {
                           //回传失败
                            PowerValue mPowerValue = new PowerValue();
                            mPowerValue.setCreated_at(MyFunc.getCurrentY_M_DHMS());
                            DBSqlHelper.getInstance().insert(DBHelper.POWER_ON_TABLE, mPowerValue);
                        }
                    });
                }else{
                    // TODO 设备无法访问Internet
                    mNetWorkStatus = false;
                    //显示网络不通提示框
                    mLinearLayoutNoNetWork.setVisibility(View.VISIBLE);
                    //隐藏跳过按钮
                    layoutSkip.setVisibility(View.GONE);
                }
                return 0;
            }
        });
    }
    public void clearWebviewCache(){
        webView.clearCache(true);
        webView.clearFormData();
        getCacheDir().delete();
    }
    //启动定时任务
    private void startTimerTask(){
        mc = new MyCountDownTimer(12000, 1000);
        mc.start();
        mHandler.sendEmptyMessageDelayed(0,12000);
    }

    private void loadUrl(String url) {
        final WebSettings settings = webView.getSettings();
        //缓存相关,关闭无痕浏览
//        clearWebviewCache();
        //播放视频，5.0 以上的手机要加这个
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        settings.setAppCacheEnabled(true);
        settings.setJavaScriptEnabled(true);// 设置WebView属性，能够执行Javascript脚本
        settings.setJavaScriptCanOpenWindowsAutomatically(true); // 设置允许JS弹窗
        settings.setDomStorageEnabled(true);//开启 DOM storage API 功能
        settings.setDatabaseEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);//无论如何都会从网络上取数据，如果没有网络，就会出现错误页面
        settings.setPluginState(WebSettings.PluginState.ON);// 支持插件
        settings.setLoadsImagesAutomatically(true);  //支持自动加载图片
        settings.setUseWideViewPort(true);  //将图片调整到适合webview的大小  无效
        settings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        settings.setSupportZoom(true);   //自动缩放
        webView.loadUrl(url);
        webView.addJavascriptInterface(new LoadingActivity.JavascriptHandler(),"android");//添加js监听 这样html就能调用客户端
        //渲染webview
        webView.setWebViewClient(new MyWebViewClient());
        webView.setWebChromeClient(new MyWebChromeClient());
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) { //监控/拦截/屏蔽返回键
            webView.goBack();
            return false;
        }
        else if(keyCode == KeyEvent.KEYCODE_MENU) {//MENU键
            //监控/拦截菜单键
            return false;
        }
//        else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {//音量减键
//            return true;
//        } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {//音量加键
//            return true;
//        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        if(mHandler != null) mHandler.removeCallbacksAndMessages(null);
//        if(webView != null){
//            webView.destroy();
//            webView = null;
//        }
    }
    //初始化串口通信
    private void initAndroidSerial(){
        //开启串口定时任务
        com = new SerialControl();
        //串口端口终端
        com.setPort("/dev/ttyS2");
        //波特率
        com.setBaudRate("9600");
        //打开串口
        PasisApplication.getInstance().openComPort(com);

//        byte[] bs = MyFunc.longToByteArray1(1,60);
//        com.send(bs);
    }

    private class SerialControl extends SerialHelper {
        public SerialControl(){
        }

        @Override
        protected void onDataReceived(final ComBean ComRecData)
        {
            Log.d("接收反馈信息", MyFunc.ByteArrToHex(ComRecData.bRec, 0, 1));
            String shutdownflag = MyFunc.ByteArrToHex(ComRecData.bRec, 0, 1);
            if(shutdownflag.equals("55")){
                mPowerOffStatus = true;//设置为已经关机状态
                if(!sendA83Status){
                    sendA83Status = true;
                    //获取本地数据库数据
                    ArrayList<BaseModel> schemes = DBSqlHelper.getInstance().select(DBHelper.SCHEME_TABLE
                            , null
                            , null
                            , "ele_shutdown_week_num asc, ele_shutdown_stime_h asc, ele_shutdown_stime_m asc", SchemeValue.class, null);
                    //判断是否有数据
                    int len = schemes.size();
                    String content = "";
                    for(int i=0;i<len;i++){
                        SchemeValue mSchemeValue = (SchemeValue) schemes.get(i);
                        content += " 第"+i+"条、ele_shutdown_id:"+mSchemeValue.ele_shutdown_id+" ele_shutdown_week:"+mSchemeValue.ele_shutdown_week+" ele_shutdown_stime:"+mSchemeValue.ele_shutdown_stime+" ele_shutdown_etime:"+mSchemeValue.ele_shutdown_etime+" ele_shutdown_stime_h:"+mSchemeValue.ele_shutdown_stime_h+" ele_shutdown_stime_m:"+mSchemeValue.ele_shutdown_stime_m+" ele_shutdown_week_num:"+mSchemeValue.ele_shutdown_week_num+" created_at:"+mSchemeValue.created_at;
                    }
                    //给服务器回传开关机日志
                    RequestCenter.sendShutDownLog(content, new DisposeDataListener(){
                        @Override
                        public void onSuccess(Object responseObj) {
                            //成功
                            dealShutdownLog();//缓存关机日志，并关机
                        }

                        @Override
                        public void onFailure(Object reasonObj) {
                            //回传失败
                            dealShutdownLog();//缓存关机日志，并关机
                        }
                    });
                }
            }
        }
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(!mNetWorkStatus){
                Log.d("网络","网络不通");
                startTimerTask();
            }
            if(mNetWorkStatus && mLoadWebviewStatus){
                //网络是通的，并且可以加载webview
                mLoadWebviewStatus = false;
                Log.d("mNetWorkStatus2 && mLoadWebviewStatus2", "开始加载webview");
                loadUrl(Router.WEB_ROOT_URL);
                mLinearLayoutNoNetWork.setVisibility(View.GONE);
                mTopWeb.setVisibility(View.VISIBLE);
                mCopyLayout.setVisibility(View.GONE);
                mBottomLauncher.setVisibility(View.GONE);
            }
        }
    };
    /**
     * 处理关机和开机事件
     */
    public static Handler mTimeHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            runShutdown();
        }
        /**
         * 处理开关机业务逻辑
         */
        private void runShutdown(){
            Log.d("SchemeManagerExist", "status:"+SchemeManager.getInstance().hasExist());
            Log.d("SchemeManagerExistId", "status:"+SchemeManager.getInstance().getE_week());
            if(SchemeManager.getInstance().hasExist() && !mShutdownFlag){
                //已储存开关机数据，并且没有新数据写入
                String task_hm = SchemeManager.getInstance().getSchemeValue().ele_shutdown_stime; //关机标准时间
//                String poweron_hm = SchemeManager.getInstance().getSchemeValue().ele_shutdown_etime;////关机开机时间
//                Long poweron_second = MyFunc.getTimeString2Long(poweron_hm+":00");//获取开机second
//                Long poweroff_second = MyFunc.getTimeString2Long(task_hm+":00");//获取关机second
//                Long second = (poweron_second - poweroff_second)/1000;
                Boolean powerOffStatus = checkPowerOff(task_hm, SchemeManager.getInstance().getSchemeValue().ele_shutdown_week_num);//判断今天是否关机
                Log.d("定时任务", "SchemeManager: 时间差："+SchemeManager.getInstance().getTimeReduce());
                Log.d("haha2", "runShutdown2: "+powerOffStatus);
                Log.d("haha", "runShutdown: "+mPowerOffStatus);
                if(powerOffStatus && !mPowerOffStatus){
//                    mPowerOffStatus = true;//设置为已经关机状态
                    Log.d("com_send", "现在开始关机,写入时间："+SchemeManager.getInstance().getTimeReduce());
                    byte[] bs = MyFunc.longToByteArray1(1,SchemeManager.getInstance().getTimeReduce());
                    for(int i=0;i<3;i++){
                        com.send(bs);
                    }
                    mTimeHandler.removeCallbacksAndMessages(null);
                    this.removeCallbacksAndMessages(null);
//                    dealShutdownLog();//缓存关机日志
                }
            }else{
                //从数据库中获取开关机数据
                if(DBHelper.getInstance().tabIsExist("ps_ele_shutdown")) {
                    Log.d("定时任务", "runShutdown: 22222222嘻嘻嘻嘻嘻嘻");
                    //判断表ps_ele_shutdown是否存在，如果存在：
                    String weekNum = MyFunc.getCurrentWeekNum();
                    //获取当前时和分，并返回数组
                    int[] hms = MyFunc.getCurrentHMIntArr();
                    Log.d("数据库查询结构", "星期："+weekNum+" 时："+Integer.toString(hms[0])+" 分："+Integer.toString(hms[1]));
                    //获取数据
                    ArrayList<BaseModel> schemes = DBSqlHelper.getInstance().select(DBHelper.SCHEME_TABLE
                            , "ele_shutdown_week_num >= ?"
                            , new String[]{weekNum}
                            , "ele_shutdown_week_num asc, ele_shutdown_stime_h asc, ele_shutdown_stime_m asc", SchemeValue.class, null);
                    //判断是否有数据
                    int len = schemes.size();
                    if (len != 0) {
                        //TODO：判断关机时间
                        Log.d("定时任务", "runShutdown: 嘻嘻嘻嘻嘻嘻");
                        Long currentTimeStamp = MyFunc.getTimeString2Long(hms[0]+":"+hms[1]+":00");//把当前时间换算成毫秒
                        for(int i=0;i<len;i++){
                            SchemeValue mSchemeValue = (SchemeValue) schemes.get(i);
                            Log.d("setrunShutdown", "ele_shutdown_stime:"+mSchemeValue.ele_shutdown_stime);
                            Long powerOff = MyFunc.getTimeString2Long(mSchemeValue.ele_shutdown_stime + ":00");//获取关机second
//                            int powerOffStatus = Integer.parseInt(mSchemeValue.ele_shutdown_week_num) - Integer.parseInt(mSchemeValue.ele_shutdown_week_num);
//                            if (powerOffStatus == 0 && !mPowerOffStatus) {
//                                //现在需要关机，处理开机时间
////                                mPowerOffStatus = true;//设置为已经关机状态
//                                setSchemeManager(schemes, i, currentTimeStamp);
//                                Log.d("开机时间和关机时间的时间差：", SchemeManager.getInstance().getTimeReduce() + "");
////                                dealShutdownLog();
//                                mShutdownFlag = false;//设置为没有新的开关机数据
//                                return;
//                            } else {
//                                //现在不需要关机，但是要缓存开关机数据
//                                if(powerOff > currentTimeStamp){
//                                    //筛选关机时间要小于当前时间
//                                    setSchemeManager(schemes,i,currentTimeStamp);
//                                    Log.d("现在不需要关机，但是要缓存开关机数据：","现在不需要关机，但是要缓存开关机数据");
//                                    mShutdownFlag = false;//设置为没有新的开关机数据
//                                    return;//退出循环
//                                }
//                            }
                            Log.d("setrunShutdown", "powerOff:"+powerOff+" currentTimeStamp:"+currentTimeStamp);
                            if(powerOff >= currentTimeStamp){
                                //筛选关机时间要小于当前时间
                                setSchemeManager(schemes,i,currentTimeStamp);
                                Log.d("现在不需要关机，但是要缓存开关机数据：","现在不需要关机，但是要缓存开关机数据");
                                mShutdownFlag = false;//设置为没有新的开关机数据
                                return;//退出循环
                            }
                        }
                    }
                }
            }
        }
        /**
         * 处理开关管理器SchemeManager，存储时间差和关机数据
         */
        private void setSchemeManager(ArrayList<BaseModel> schemes, int i, Long currentTimeStamp){
            SchemeValue mSchemeValue = (SchemeValue) schemes.get(i);
            int len = schemes.size();
            Long powerOff = MyFunc.getTimeString2Long(mSchemeValue.ele_shutdown_stime + ":00");//获取关机second
            Long powerOn = MyFunc.getTimeString2Long(mSchemeValue.ele_shutdown_etime + ":00");//获取开机second
            Long second;//开机时间和关机时间的时间差
            if (powerOn <= currentTimeStamp) {
                //如果开机时间小于当前时间，说明是下条数据的开机时间,7:50:00<7:50:30
                if(len > 1) {
                    SchemeValue nextSchemeValue = (SchemeValue) schemes.get(i + 1);
                    Log.d("setSchemeManager", nextSchemeValue.ele_shutdown_id+":"+nextSchemeValue.ele_shutdown_week_num);
                    int nextWeekNum = Integer.parseInt(nextSchemeValue.ele_shutdown_week_num) - Integer.parseInt(mSchemeValue.ele_shutdown_week_num);
                    if (nextWeekNum == 0) {
                        //表示关机和开机是同一天，已测试通过
                        Log.d("开关机是同一天", "同一天: 同一天");
                        mSchemeValue.setEle_shutdown_etime(nextSchemeValue.ele_shutdown_etime);
                        SchemeManager.getInstance().setSchemeValue(mSchemeValue);//缓存关机信息
                        Long nextPowerOn = MyFunc.getTimeString2Long(nextSchemeValue.ele_shutdown_etime + ":00");//获取管机second
                        second = (nextPowerOn - powerOff) / 1000;
                        SchemeManager.getInstance().setTimeReduce(second);//缓存开关机时间差信息
                        SchemeManager.getInstance().setE_week(nextSchemeValue.ele_shutdown_week);//缓存开机星期信息
                    } else {
                        //开机和关机不是同一天
                        Long currentDayLastTime = MyFunc.getTimeString2Long("24:00:00");
                        second = ((currentDayLastTime - powerOff)
                                + MyFunc.getTimeString2Long(nextSchemeValue.getEle_shutdown_etime() + ":00")
                                + ((nextWeekNum - 1) * 24 * 60 * 60 * 1000)) / 1000;
                        SchemeManager.getInstance().setSchemeValue(mSchemeValue);//缓存关机信息
                        Log.d("开关机不是同一天", "不是同一天: 不是同一天 "+second);
                        SchemeManager.getInstance().setTimeReduce(second);//缓存开关机时间差信息
                        SchemeManager.getInstance().setE_week(nextSchemeValue.ele_shutdown_week);//缓存开机星期信息
                    }
                }else{
                    //说明是下周的今天开机,已测试通过
                    Log.d("启动周任务", "setSchemeManager: 下周");
                    //可能会存在俩种情况，1.全周只有设置开关机，2.起始周的周末关机，下周开机
                    ArrayList<BaseModel> schemesAll = DBSqlHelper.getInstance().select(DBHelper.SCHEME_TABLE
                            , null
                            , null
                            , "ele_shutdown_week_num asc", SchemeValue.class, null);
                    if(schemesAll.size() > 1){
                        //2.起始周的周末关机，下周开机
                        Log.d("起始周的周末关机，下周开机", "起始周的周末关机，下周开机 ");
                        SchemeValue firstSchemeValue = (SchemeValue) schemesAll.get(0);
                        Long currentDayLastTime = MyFunc.getTimeString2Long("24:00:00");
                        int shutupDayNum = 6 - Integer.parseInt(mSchemeValue.getEle_shutdown_week_num())+Integer.parseInt(firstSchemeValue.getEle_shutdown_week_num());
                        Log.d("reduce", "reduce: "+Integer.parseInt(mSchemeValue.getEle_shutdown_week_num()));
                        Log.d("plus", "plus: "+Integer.parseInt(firstSchemeValue.getEle_shutdown_week_num()));
                        second = ((currentDayLastTime - powerOff)
                                + MyFunc.getTimeString2Long(firstSchemeValue.getEle_shutdown_etime() + ":00")
                                + (shutupDayNum * 24 * 60 * 60 * 1000)) / 1000;
                        SchemeManager.getInstance().setSchemeValue(mSchemeValue);//缓存关机信息
                        SchemeManager.getInstance().setTimeReduce(second);//缓存开关机时间差信息
                        SchemeManager.getInstance().setE_week(firstSchemeValue.ele_shutdown_week);//缓存开机星期信息
                    }else{
                        //1.全周只设置一次开关机
                        Log.d("全周只设置一次开关机", "全周只设置一次开关机");
                        second = ((6 * 24 * 60 * 60 * 1000) + powerOn)/1000;
                        SchemeManager.getInstance().setSchemeValue(mSchemeValue);//缓存关机信息
                        SchemeManager.getInstance().setTimeReduce(second);//缓存开关机时间差信息
                        SchemeManager.getInstance().setE_week(mSchemeValue.ele_shutdown_week);//缓存开机星期信息
                    }
                }
            } else {
                Log.d("开机时间大于当前时间", "------开机时间大于当前时间------");
                //关机时间9点，当前时间8：50
                SchemeManager.getInstance().setSchemeValue(mSchemeValue);//缓存关机信息
                if((powerOn - powerOff) < 0){
                    //7:50-17:10
                    if(len > 1) {
                        SchemeValue nextSchemeValue = (SchemeValue) schemes.get(i + 1);
                        int nextWeekNum = Integer.parseInt(nextSchemeValue.ele_shutdown_week_num) - Integer.parseInt(mSchemeValue.ele_shutdown_week_num);
                        Long currentDayLastTime = MyFunc.getTimeString2Long("24:00:00");
                        second = ((currentDayLastTime - powerOff)
                                + MyFunc.getTimeString2Long(nextSchemeValue.getEle_shutdown_etime() + ":00")
                                + ((nextWeekNum - 1) * 24 * 60 * 60 * 1000)) / 1000;
                        SchemeManager.getInstance().setTimeReduce(second);//缓存开关机时间差信息
                        SchemeManager.getInstance().setE_week(nextSchemeValue.ele_shutdown_week);//缓存开机星期信息
                    }else{
                        //处理每周的设置关机的最后一天，和下次开机的每周初
                        ArrayList<BaseModel> schemesAll = DBSqlHelper.getInstance().select(DBHelper.SCHEME_TABLE
                                , null
                                , null
                                , "ele_shutdown_week_num asc", SchemeValue.class, null);
//2018年12月7日添加，为了修复包钢十一小星期五关机，下星期一开机，出现负数
                        SchemeValue firstSchemeValue = (SchemeValue) schemesAll.get(0);
                        Long currentDayLastTime = MyFunc.getTimeString2Long("24:00:00");
                        int shutupDayNum = 6 - Integer.parseInt(mSchemeValue.getEle_shutdown_week_num())+Integer.parseInt(firstSchemeValue.getEle_shutdown_week_num());
                        second = ((currentDayLastTime - powerOff)
                                + MyFunc.getTimeString2Long(firstSchemeValue.getEle_shutdown_etime() + ":00")
                                + (shutupDayNum * 24 * 60 * 60 * 1000)) / 1000;
                        SchemeManager.getInstance().setSchemeValue(mSchemeValue);//缓存关机信息
                        SchemeManager.getInstance().setTimeReduce(second);//缓存开关机时间差信息
                        SchemeManager.getInstance().setE_week(firstSchemeValue.ele_shutdown_week);//缓存开机星期信息
//2018年12月7日删除，为了修复包钢十一小星期五关机，下星期一开机，出现负数
//                        SchemeValue nextSchemeValue = (SchemeValue) schemesAll.get(0);
//                        int nextWeekNum = Integer.parseInt(nextSchemeValue.ele_shutdown_week_num) - Integer.parseInt(mSchemeValue.ele_shutdown_week_num);
//                        Long currentDayLastTime = MyFunc.getTimeString2Long("24:00:00");
//                        second = ((currentDayLastTime - powerOff)
//                                + MyFunc.getTimeString2Long(nextSchemeValue.getEle_shutdown_etime() + ":00")
//                                + ((nextWeekNum - 1) * 24 * 60 * 60 * 1000)) / 1000;
//                        SchemeManager.getInstance().setTimeReduce(second);//缓存开关机时间差信息
//                        SchemeManager.getInstance().setE_week(nextSchemeValue.ele_shutdown_week);//缓存开机星期信息
                    }
                }else{
                    second = (powerOn - powerOff) / 1000;
                    SchemeManager.getInstance().setTimeReduce(second);//缓存开关机时间差信息
                    SchemeManager.getInstance().setE_week(mSchemeValue.ele_shutdown_week);//缓存开机星期信息
                }

            }
        }
    };

    /**
     * 处理关机日志
     */
    public void dealShutdownLog(){
        ShutdownValue mShutdownValue = new ShutdownValue();
        mShutdownValue.setEle_reduce_time(String.valueOf(SchemeManager.getInstance().getTimeReduce()));
        mShutdownValue.setEle_shutdown_s_week(SchemeManager.getInstance().getSchemeValue().ele_shutdown_week);
        mShutdownValue.setEle_shutdown_e_week(SchemeManager.getInstance().getE_week());
        mShutdownValue.setEle_shutdown_stime(SchemeManager.getInstance().getSchemeValue().ele_shutdown_stime);
        mShutdownValue.setEle_shutdown_etime(SchemeManager.getInstance().getSchemeValue().ele_shutdown_etime);
        mShutdownValue.setCreated_at(MyFunc.getCurrentYMDHMS());
        DBSqlHelper.getInstance().insert(DBHelper.SHUT_TABLE, mShutdownValue);
        shutDownMachine();
    }

    /**
     * 根据小时和分钟，判断是否关机
     * @param hm
     * @return
     */
    private static boolean checkPowerOff(String hm, String currentWeekNum){
        Long time = System.currentTimeMillis();  //获取当前时间错
        String Current_hm = MyFunc.getTranslateHM(time); //获取当前时间(时分)
        String weekNum = MyFunc.getCurrentWeekNum();
        if(weekNum.equals(currentWeekNum)){
            //如查询本地数据获取的星期等于当前的星期
            if(Current_hm.equals(hm)){
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    /**
     * 开启新线程监听关机和开机
     */
    public class TimeThread extends Thread{
        public TimeThread(){}

        public void run(){
            super.run();
            while(!isInterrupted()){
                try {
                    Thread.sleep(1000L);
                    Message localMessage = new Message();
                    localMessage.what = 1;
                    LoadingActivity.mTimeHandler.sendMessage(localMessage);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * JS接口回调
     */
    class JavascriptHandler {
        @JavascriptInterface
        public String getMachineUniqueSerialNumber() {
            return mSerialNumber;
        }
        @JavascriptInterface
        public void shutdownApi(String json){
            Log.d("webview回传数据", json);
            //[{"ele_shutdown_id":6,"ele_shutdown_week":"星期一","ele_shutdown_stime":"10:00","ele_shutdown_etime":"10:05","ele_shutdown_stime_h":10,"ele_shutdown_stime_m":0,"ele_shutdown_week_num":1,"created_at":"2018-09-18 11:47:22"},{"ele_shutdown_id":5,"ele_shutdown_week":"星期一","ele_shutdown_stime":"2:00","ele_shutdown_etime":"11:00","ele_shutdown_stime_h":2,"ele_shutdown_stime_m":0,"ele_shutdown_week_num":1,"created_at":"2018-09-18 11:46:40"}]
            if(json == null || json.equals("null") || json.isEmpty()){
                Log.d("清空数据", "清空ps_ele_shutdown表数据");
                DBHelper.getInstance().delete(DBHelper.SCHEME_TABLE, null, null);//清除数据库
                SchemeManager.getInstance().removeScheme();
                mPowerOffStatus = false;
            }else{
                Log.d("缓存数据", "缓存ps_ele_shutdown表数据");
                try {
                    ArrayList<SchemeValue> schemes = new ArrayList<>();
                    JSONArray object = new JSONArray(json);
                    for(int i=0;i<object.length();i++){
                        SchemeValue schemeValue = new SchemeValue();
                        JSONObject mJson = object.getJSONObject(i);
                        schemeValue.setEle_shutdown_id(mJson.getString("ele_shutdown_id"));
                        schemeValue.setEle_shutdown_week(mJson.getString("ele_shutdown_week"));
                        schemeValue.setEle_shutdown_week_num(mJson.getString("ele_shutdown_week_num"));
                        schemeValue.setEle_shutdown_stime(mJson.getString("ele_shutdown_stime"));
                        schemeValue.setEle_shutdown_stime_h(mJson.getString("ele_shutdown_stime_h"));
                        schemeValue.setEle_shutdown_stime_m(mJson.getString("ele_shutdown_stime_m"));
                        schemeValue.setEle_shutdown_etime(mJson.getString("ele_shutdown_etime"));
                        schemeValue.setCreated_at(mJson.getString("created_at"));
                        schemes.add(schemeValue);
                    }
                    DBSqlHelper.getInstance().delete(DBHelper.SCHEME_TABLE,null,null);//清空数据库表
                    DBSqlHelper.getInstance().insert(DBHelper.SCHEME_TABLE, schemes);
                    mShutdownFlag = true;//标志为true，说明有新的开关机数据写入sqlite
                    SchemeManager.getInstance().removeScheme();
                    mPowerOffStatus = false;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        @JavascriptInterface
        public void showLog(){
            Intent intent = new Intent(LoadingActivity.this, MainActivity.class);
            startActivity(intent);
        }
        @JavascriptInterface
        public void updateAndroidVersion(){
            checkAndroidVersion();
        }
        @JavascriptInterface
        public String getAndroidVersion(){
            int version = getLocalVersion(LoadingActivity.this);
            return version+"";
        }
        @JavascriptInterface
        public void clearAndroidWebviewCache(){
            clearWebviewCache();
        }
        @JavascriptInterface
        public void changeTouchStatusBarTask(){
            if(statusBarFlag){
                statusBarFlag = false;
                //禁用下拉状态栏
                SPManager.getInstance().putBoolean("statusBarFlag", statusBarFlag);
            }else{
                statusBarFlag = true;
                //启用下拉状态栏
                SPManager.getInstance().putBoolean("statusBarFlag", statusBarFlag);
            }
            restartApp(LoadingActivity.this);
        }
    }

    /**
     * webView渲染类
     */
    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // TODO Auto-generated method stub
            view.loadUrl(url);
            return true;
        }
        @Override
        public void onReceivedError(WebView var1, int var2, String var3, String var4) {
            progressBar.setVisibility(View.GONE);

        }
    }

    private class MyWebChromeClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                progressBar.setVisibility(View.GONE);
                return;
            }
            progressBar.setVisibility(View.VISIBLE);
            progressBar.setProgress(newProgress);
        }
    }


    /**
     * 继承 CountDownTimer 防范
     *
     * 重写 父类的方法 onTick() 、 onFinish()
     */
    class MyCountDownTimer extends CountDownTimer {
        /**
         *
         * @param millisInFuture
         * 表示以毫秒为单位 倒计时的总数
         *
         * 例如 millisInFuture=1000 表示1秒
         *
         * @param countDownInterval
         * 表示 间隔 多少微秒 调用一次 onTick 方法
         *
         * 例如: countDownInterval =1000 ; 表示每1000毫秒调用一次onTick()
         *
         */
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }
        public void onFinish() {
            tv_second.setText("正在");
        }
        public void onTick(long millisUntilFinished) {
            long onTickSecond =  millisUntilFinished / 1000;
            tv_second.setText(onTickSecond+"");
            Log.d("网络", "onTick: "+onTickSecond);
            if(!mNetWorkStatus){
                //网络不通
                Log.d("网络2","网络不通");
                checkNetWork();
            }else{
                mLinearLayoutNoNetWork.setVisibility(View.GONE);
            }
        }
    }
}
